"""
百度API 文字转语音
"""

from aip import AipSpeech
from tools.loggingConfig import logger


def baiduAudioApi(text, savePath):
    """
    百度API 文字转语音
    @param text: 文字内容
    @param savePath: audio保存地址
    """
    """ 你的 APPID AK SK """
    APP_ID = '28550998'
    API_KEY = 'fAfX4C5WQHm0ANYSn0MnQXYV'
    SECRET_KEY = 'HjCOQI0kn9WpT62a4uPwhDuMeVhoyPD5'
    client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

    maxByteSize = 1000
    cutList = []
    start = 0
    for i in range(1, len(text) + 1):
        cutText = text[start:i]
        size = len(cutText.encode())
        if size >= maxByteSize:
            cutList.append(cutText)
            start = i
        elif i == len(text):
            cutList.append(cutText)

    audioList = []
    for text in cutList:
        result = client.synthesis(text, 'zh')
        # 识别正确返回语音二进制 错误则返回dict 参照下面错误码
        if not isinstance(result, dict):
            audioList.append(result)
        else:
            logger.error(f"百度API合成语音出错: {savePath} {text}")
            raise ValueError

    with open(savePath, 'wb') as f:
        for audio in audioList:
            f.write(audio)
